package com.hank.jms.topic;

import com.hank.common.Constant;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class TopicReceiver {
    public static void main(String[] args){
        //创建连接工厂
        ConnectionFactory connectionFactory=new ActiveMQConnectionFactory(Constant.BROKER_URL);
        Connection connection= null;
        try {
            //通过工厂获取一个连接
            connection = connectionFactory.createConnection();
            connection.start();

            //通过连接创建一个会话,并默认设开启事务,自动确认消息
            Session session=connection.createSession(Boolean.TRUE,Session.AUTO_ACKNOWLEDGE);
            //通过会话构建一个目的地
            Destination destination=session.createTopic("no_persistent_topic");
            //再通过session创建一个消息发送者，并设定发送目的地对象
            MessageConsumer consumer=session.createConsumer(destination);

//            //获取消息
            for (int i = 0; i < 50; i++) {
                TextMessage message=(TextMessage)consumer.receive();
                System.out.println("Receiver Topic TextMessage >>"+message.getText());
                session.commit();
            }
            session.close();
            connection.close();

        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
            try{
                if(connection!=null){
                    connection.close();
                    connection=null;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }
}
